#!/bin/bash
# MSYS2 下编译thrift脚本
# MSYS2 下载 http://repo.msys2.org/distrib/x86_64/msys2-base-x86_64-20201109.tar.tar.xz
# 安装依赖库和必须的工具
#pacman --needed --noconfirm -S unzip bison flex make mingw-w64-x86_64-openssl \
#            mingw-w64-x86_64-boost mingw-w64-x86_64-cmake \
#            mingw-w64-x86_64-toolchain mingw-w64-x86_64-zlib

###################
sh_folder=$(dirname $(readlink -f $0))
# 定义编译的版本类型(DEBUG|RELEASE)
build_type=RELEASE
[[ "${BUILD_TYPE^^}" =~ DEBUG|RELEASE ]] && build_type=${BUILD_TYPE^^}

echo build_type=$build_type
[ -n "$PREFIX" ] && install_prefix="$PREFIX"
[ -z "$PREFIX" ] && install_prefix=$sh_folder/dist/thrift-$(g++ -dumpmachine)
[ -e "$install_prefix" ] && rm -fr "$install_prefix"

[ -n "$THRIFT_FOLDER" ] && [ -d "$THRIFT_FOLDER" ] && thrift_folder=$THRIFT_FOLDER
[ -z "$THRIFT_FOLDER" ] && [ -d $sh_folder/thrift ] && thrift_folder=$sh_folder/thrift
[ -z "$thrift_folder" ] && echo "NOT DEFINED thrift_folder" && exit 255

[ -n "$PROJECT_FOLDER" ] && prj_folder="$PROJECT_FOLDER"
[ -z "$PROJECT_FOLDER" ] && prj_folder=$sh_folder/build/thrift-$(g++ -dumpmachine)

[ -d $prj_folder ] && rm -fr $prj_folder
mkdir -p $prj_folder || exit 

pushd $prj_folder || exit

cmake $thrift_folder -G"MinGW Makefiles" -DCMAKE_MAKE_PROGRAM=/mingw64/bin/mingw32-make \
	-DCMAKE_BUILD_TYPE=$build_type \
   -DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc.exe \
   -DCMAKE_CXX_COMPILER=x86_64-w64-mingw32-g++.exe \
   -DWITH_BOOSTTHREADS=ON \
   -DWITH_C_GLIB=OFF \
   -DWITH_LIBEVENT=OFF \
   -DWITH_SHARED_LIB=OFF \
   -DWITH_STATIC_LIB=ON \
   -DWITH_JAVA=OFF \
   -DWITH_PYTHON=OFF \
   -DCMAKE_INSTALL_PREFIX=$install_prefix \
   -DBUILD_TESTING=OFF \
   -DBUILD_TUTORIALS=OFF \
   -DWITH_BOOST_STATIC=ON \
   -DCMAKE_CXX_FLAGS="-static-libgcc -static-libstdc++" \
   || exit 
   
cmake --build . --target install -- -j8

popd
